import { ComponentMap } from '@/config/ComponentMap'
import {
  isOptionsProps,
  isPicTitleDescStatusArray,
  isStringArray,
  isValueStatusArray,
  type OptionsProps,
  type Status,
  type SurveyDBData,
  type TextProps,
  type VueComType,
} from '@/types'
import type { TableColumnCtx } from 'element-plus'

// 计算滚动条是否到底部或者顶部
export function handleScroll(event: WheelEvent) {
  const target = event.currentTarget as HTMLElement

  // 使用 Math.round() 将值转换为整数
  const scrollTop = Math.round(target.scrollTop)
  const scrollHeight = Math.round(target.scrollHeight)
  const clientHeight = Math.round(target.clientHeight)

  const isAtTop = scrollTop === 0
  const isAtBottom = scrollHeight - scrollTop === clientHeight

  if ((isAtTop && event.deltaY < 0) || (isAtBottom && event.deltaY > 0)) {
    event.preventDefault()
    event.stopPropagation()
  }
}
// 将时间戳转为日期格式
// 日期格式化函数
export function formatDate(
  row: SurveyDBData,
  column: TableColumnCtx<SurveyDBData>,
  cellValue: number,
) {
  const options: Intl.DateTimeFormatOptions = {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  }
  return new Intl.DateTimeFormat('zh-CN', options).format(new Date(cellValue))
}

export function gerTextStatus(props: TextProps) {
  return props.status
}
export function gerStringStatus(props: OptionsProps) {
  if (props && isStringArray(props.status)) {
    return props.status
  }
}
export function gerPicTitleDescStatusArr(props: OptionsProps) {
  if (props && isPicTitleDescStatusArray(props.status)) {
    return props.status
  }
}
export function gerValueStatusArr(props: OptionsProps) {
  if (props && isValueStatusArray(props.status)) {
    return props.status
  }
}
export function gerCurrentStatus(props: OptionsProps) {
  return props.currentStatus
}
export function gerStringStatusByCurrentStatus(props: OptionsProps) {
  if (props && isStringArray(props.status)) {
    return props.status[props.currentStatus]
  }
}
export function getValueStatusByCurrentStatus(props: OptionsProps) {
  if (
    props &&
    isOptionsProps(props) &&
    (isValueStatusArray(props.status) || isPicTitleDescStatusArray(props.status))
  ) {
    return props.status[props.currentStatus]
  }
}

/**
 * 还原组件状态，因为保存的时候丢失了组件的引用
 * @param coms 题目数组
 */
export const restoreComponentStatus = (coms: Status[]) => {
  coms.forEach((com) => {
    // 业务组件还原
    com.type = ComponentMap[com.name]
    for (const key in com.status) {
      const name = com.status[key].name
      com.status[key].editCom = ComponentMap[name]
    }
  })
}
